package com.grocery.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alipay.api.AlipayApiException;
import com.grocery.bean.*;
import com.grocery.dao.*;
import com.grocery.service.IOrderService;
import com.grocery.util.PaymentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class OrderService implements IOrderService {
    @Autowired
    ProductDao productDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    AddressDao addressDao;
    @Autowired
    CartDao cartDao;
    @Transactional
    @Override
    public int addOrder(List<Integer> ids, List<Integer> numbers, Integer addressid, Integer userid) {
        //参数检查
        // 1.两个集合中的数据数量要一样
        // 2.numbers中的数字不能小于1
        int idssize=-1;
        int numberssize=-1;
        if(ids!=null&&numbers!=null){
            idssize=ids.size();
            numberssize=numbers.size();
            if(!(idssize>0&&numberssize>0&&idssize==numberssize)){
                throw new RuntimeException("参数异常");
            }
        }else{
            throw new RuntimeException("参数异常");
        }

        //获取商品数据
        List<Orderdetail> orderdetailList=new ArrayList<>();
        BigDecimal total=new BigDecimal(0);
        int id=0;
        int number=0;
        for(int i=0;i<ids.size();i++){
            id=ids.get(i);
            number=numbers.get(i);//商品id值
            Product pro=productDao.getByID(id);
            if (pro==null){
                throw new RuntimeException("参数异常");
            }
            Orderdetail orderdetail=new Orderdetail();
            orderdetail.setImgurl(pro.getDefaultimg());
            orderdetail.setPrice(pro.getPrice());
            orderdetail.setNumber(number);
            orderdetail.setProductname(pro.getName());
            orderdetail.setProductid(pro.getId());
            orderdetailList.add(orderdetail);
            //计算总价格
            total=total.add(pro.getPrice().multiply(new BigDecimal(number)));

        }
        //封装订单
        Order order=new Order();
        order.setCode("5201369991499114");
        order.setMoney(total);
        order.setUserId(userid);
        //保存  获取订单id(自增长)
        orderDao.addOrder(order);
        int orderid=order.getId();//获取自增长主键
        for(Orderdetail detail:orderdetailList){
            detail.setOrderid(orderid);
        }
        //封装订单明细
        orderDao.addOrderDetail(orderdetailList);
        //获取地址
        Useraddress useraddress=addressDao.getAddressByID(addressid);
        if(useraddress==null){

        }
        StringBuilder strB=new StringBuilder();
        strB.append(useraddress.getProvince());
        strB.append("-");
        strB.append(useraddress.getCity());
        strB.append("-");
        strB.append(useraddress.getArea());
        strB.append("-");
        strB.append(useraddress.getAddress());
        String address=strB.toString();
        //处理地址
        Orderaddress orderaddress=new Orderaddress();
        orderaddress.setOrderid(orderid);
        orderaddress.setAddress(address);
        orderaddress.setName(useraddress.getName());
        orderaddress.setTel(useraddress.getTelephone());
        //封装地址
        orderDao.addOrderAddress(orderaddress);
        //删除购物车中的数据
//        for(Integer item:ids){
//            Cart cart=new Cart();
//            cart.setProductid(id);
//            cart.setProductid(item);
//            cartDao.delete(cart);
//        }
        return orderid;
    }

    @Override
    public String payment(Integer id) {
        Order order=orderDao.getOrderByID(id);
        if(order==null){
            throw new RuntimeException("订单不存在");
        }
        if(order.getState()==-1){
            throw new RuntimeException("订单已失效");
        }
        if(order.getState()==1){
            throw new RuntimeException("订单已支付");
        }
        //准备支付--生成二维码
        String url=null;
        try {
            url=PaymentUtil.payment(order);
        } catch (Exception e) {
            throw new RuntimeException("支付服务异常");
        }
        //生成二维码图片
        BufferedImage img=QrCodeUtil.generate(url, 300, 300);
        //将图片转成Base64编码
        String qrcode=ImgUtil.toBase64(img,"png");
        return qrcode;
    }

    public int paymentSuccess(HashMap map){
        //检查订单是否存在,是否是阿里后台的回调
        String code=(String)map.get("out_trade_no");
        System.out.println("订单号:"+code);
        return orderDao.paymentSuccess(code);
    }

    @Override
    public Order getOrderByID(Integer id) {
        return orderDao.getOrderByID(id);
    }

    @Override
    public int cancelOrder() {
        return orderDao.cancelorder();
    }

    @Override
    public List<Order> getAllOrder() {
        return orderDao.getAllOrder();
    }

    @Override
    public int getCount(String text) {
        return orderDao.getCount(text);
    }

    @Override
    public int editState(Integer code, Integer state) {
        return orderDao.editState(code,state);
    }

    @Override
    public List<Order> getOrderByuserID(Integer userid) {
        return orderDao.getOrderByuserID(userid);
    }

}
